#include <my_header.h>
// 群聊客户端
/* Usage: ./4_client_chat */
int main(void){                                  
    char *ip = "192.168.229.128";
    char *port = "8080";

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(socket_fd, -1, "socket");

    struct sockaddr_in client_addr;
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(atoi(port));
    client_addr.sin_addr.s_addr = inet_addr(ip);

    int res_conn = connect(socket_fd, (struct sockaddr *)&client_addr, sizeof(client_addr));
    ERROR_CHECK(res_conn, -1, "connect");

    fd_set set;
    while(1)
    {
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        FD_SET(socket_fd, &set);

        int res_sel = select(socket_fd + 1, &set, NULL, NULL, NULL);
        ERROR_CHECK(res_sel, -1, "select");

        if(FD_ISSET(STDIN_FILENO, &set))
        {
            char buf[60] = {0};
            int res_read = read(STDIN_FILENO, buf, sizeof(buf));
            if(res_read == 0)
            {
                printf("服务器断开连接\n");
                break;
            }
            int res_send = send(socket_fd, buf, sizeof(buf), 0);
            ERROR_CHECK(res_send, -1, "send");
        }

        if(FD_ISSET(socket_fd, &set))
        {
            char buf[60] = {0};
            int res_recv = recv(socket_fd, buf, sizeof(buf), 0);
            ERROR_CHECK(res_recv, -1, "recv");
            if(res_recv == 0)
            {
                printf("服务器已断开连接 \n");
                break;
            }
            printf("client message:%s\n", buf);
        }
    }
    close(socket_fd);
    return 0;
}


